<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/9/13 17:48
 */

namespace App\Service\System;


use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\Logo\Logo;
class QrCodeService
{
    /**
     * 生成二维码
     * @param string $uri
     * @param int $size
     * @param int $margin
     * @param string $logo
     * @return string
     */
    public function createQrCode(string $data,int $size = 400, int $margin = 20,string $logo = "")
    {

        $writer = new PngWriter();
        $qrCode = new QrCode(
            data: $data,
            encoding: new Encoding('UTF-8'),
            errorCorrectionLevel: ErrorCorrectionLevel::Low,
            size: $size,
            margin: $margin,
            roundBlockSizeMode: RoundBlockSizeMode::Margin,
            foregroundColor: new Color(0, 0, 0),
            backgroundColor: new Color(255, 255, 255)
        );
        if(!empty($logo))
        {
            $logo = new Logo(
                path: $logo,
                resizeToWidth: 50,
                punchoutBackground: true
            );
            $result = $writer->write($qrCode, $logo);
        }else{
            $result = $writer->write($qrCode);
        }
        return $result->getDataUri();

    }
}